---
title: ''
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
- \usepackage{caption}
- \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, readr, tidyr, glue, argparse, here, stringr, dplyr, knitr, kableExtra, forcats, testthat);

# Working directory and command line argument setup
task_output = "primary_outcomes_table"
current_script = paste0("generate_tables_and_figures/gen_", task_output, "/src/gen_", task_output, ".Rmd")
here::i_am(current_script)
source(here::here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "RESULTS",
  "FWER",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()

```


```{r}

results <- read_csv(cl_args$RESULTS, show_col_types = F)
expect_equal(length(unique(results$covariate_set)), 1)

fwer <- read_csv(cl_args$FWER) %>%
  select(outcome, window, p_fwer, fdrq)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(outcome = value)

config <- read_yaml(cl_args$CONFIG_FILE)

source('../R/table_functions.R')
table_config <- read_yaml('../hand/tables_config.yaml')

```

\blandscape
```{r}

beta_se_digits <- table_config$digits$beta_se

# Filter to window and outcomes
outcomes_table <- results %>%
  left_join(fwer, by = c("outcome", "window")) %>%
  filter(window == config$window) %>%
  filter(outcome %in% config$outcomes) %>%
  mutate(outcome = fct_relevel(outcome, config$outcomes)) %>%
  arrange(outcome) %>%
  mutate(outcome_order = row_number()) %>%
  left_join(ylabels, by = "outcome") %>%
  mutate(pct_change_tot = beta_tot / ccm_tot) %>%
  mutate(label = case_when(outcome == "i_three_components" ~ " ",
                           TRUE ~ label),
         pct_change_tot = as.character(sprintf("%.0f%%", pct_change_tot * 100)),
         across(.cols = where(is.numeric),
                .fns = ~fmt(.x, decimals = beta_se_digits)),
         across(.cols = c(p_fwer, fdrq),
                .fns = ~na_if(.x, "NA")))

# Stack standard errors under betas in parentheses
beta_se_stack <- stack_stderrs_under_betas(outcomes_table) %>%
  select(all_of(c(names(config$columns), 'pct_change_tot'))) %>% 
  mutate(pval_itt=as.character(round(as.numeric(pval_itt), 3)),
         p_fwer=as.character(round(as.numeric(p_fwer), 3)),
         fdrq=as.character(round(as.numeric(fdrq), 3)))

# Make table
table <- beta_se_stack %>%
  select(-pct_change_tot) %>%
  mutate(
    pval_itt = round(as.numeric(pval_itt), 3),
    p_fwer = round(as.numeric(p_fwer), 3),
    fdrq = round(as.numeric(fdrq), 3)
  ) %>% 
  kable(booktabs = table_config$booktabs, 
        longtable = table_config$longtable,
        col.names = unlist(config$columns),
        align = c(table_config$alignment$text, 
                  rep(table_config$alignment$numeric, 
                      length(config$columns) - 1))) %>% 
  kable_styling(font_size = table_config$font_size) %>%
  group_rows("Primary Index of Serious Violence", 1, 2) %>%
  group_rows("Primary Outcome Components, Counts", 3, nrow(beta_se_stack)) %>%
  add_header_above(config$add_header_above) %>% 
  column_spec(1, width = table_config$col_width$text) %>%
  column_spec(2:length(config$columns), 
              width = table_config$col_width$numeric,
              latex_valign = "m") 

table

# SAVE

timestamp <- get_timestamp()
task_output <- "outcomes_primary" # To match what is on overleaf already
writeLines(table, paste0(cl_args$OUT_DIR, "/", task_output, "_up_to_date.tex"))
writeLines(table, paste0(cl_args$OUT_DIR, "/", task_output, "_", timestamp, ".tex"))

```

\elandscape